package com.yuanfeng.commoms.rocketmq;

import com.alibaba.fastjson.JSON;
import com.yuanfeng.commoms.rocketmq.config.JmsConfig;
import com.yuanfeng.commoms.rocketmq.producer.MqOrderlyProducer;
import com.yuanfeng.commoms.util.IpUtils;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author Stranger
 * @date 2023/4/10 11:09
 */
@Component
public class MqSendUtils {


    @Autowired
    private MqOrderlyProducer mqOrderlyProducer;

    @Autowired
    private static MqSendUtils mqSendUtils;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        mqSendUtils = this;
        mqSendUtils.mqOrderlyProducer = this.mqOrderlyProducer;

    }
    /**
     * mq发送商品消息
     * @param map
     */
    public static void mqSendGoods(Map<String,Object> map){
        try {
            map.put("ip", IpUtils.getIpAddress());
            Message message = JmsConfig.Utils.buildDefaultMessage (JSON.toJSONString(map));
            mqSendUtils.mqOrderlyProducer.sendMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * mq发送更新ES商品消息
     * @param map
     */
    public static void mqSendGoodsByEs(Map<String,Object> map){
        try {
            map.put("ip", IpUtils.getIpAddress());
            Message message = JmsConfig.Utils.buildEsMessage (JSON.toJSONString(map));
            mqSendUtils.mqOrderlyProducer.getProducerGroup(JmsConfig.PRODUCER_GOODS_ES_GROUP);
            mqSendUtils.mqOrderlyProducer.sendMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * mq发送用户操作日志消息
     *
     * @param map
     */
    public static void mqSendSysLog(Map<String, Object> map) {
        try {
            map.put("ip", IpUtils.getIpAddress());
            Message message = JmsConfig.Utils.buildSysLogMessage(JSON.toJSONString(map));
            mqSendUtils.mqOrderlyProducer.getProducerGroup(JmsConfig.PRODUCER_SYS_LOG_GROUP);
            mqSendUtils.mqOrderlyProducer.sendAsyMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
